<?
class Admin extends CI_Model
{
	function __construct()
	{
		parent::__construct();
		if (!$this->user->id)
			redirect('/admin/login');
		elseif (!($this->user->data->pAdmin) && !($this->user->data->pModer))
			redirect();
	}

	function getArticle($id = 0)
	{
		if (!($id = abs($id)))
			return false;
		
		$this->db->where('id', $id);
		//$this->db->where('dDeleted', 0);
		$res = $this->db->get('article')->row();
		
		return $res;
	}

	function getArticles($ids = array(), $order = true, $deleted = false)
	{
		if (is_array($ids) && sizeof($ids))
			$this->db->where_in('id', $ids);
			elseif (abs($ids))
			$this->db->where('id', abs($ids));
		if ($order)
			$this->db->order_by('tBlog');
		if ($deleted)
			$this->db->where('dDeleted >', 0);
			else
			$this->db->where('dDeleted', 0);
		return $this->db->get('article')->result();
	}

	function saveArticle($post = array())
	{
		if (!is_arr($post) || empty($post['name']) || !isset($post['address']))
			return false;

		$id = (isset($post['id']))?abs($post['id']):0;
		
		if (isset($post['delete']))
		{
			if (!($id))
				return false;
			
			$this->db->where('id', $id);
			return $this->db->update('page', array(
				'dDeleted' => now(),
				'tUserDeleted' => $this->user->id
			));
		}

		if (empty($post['text']))
		{
			if ($post['inputType'] == 'markitup')
			{
				$post['text'] = $post['text_m'];
				if (isset($post['stext_m']))
					$post['shorttext'] = $post['stext_m'];
			}
			elseif ($post['inputType'] == 'tinymce')
			{
				$post['text'] = $post['text_t'];
				if (isset($post['stext_t']))
					$post['shorttext'] = $post['stext_t'];
			}
			else
				return false;
		}

		if ($this->existsUrl($post['address'], $id))
			die('Этот короткий адрес уже используется: '.$post['address']);

		$upd = array(
			'pName' => $post['name'],
			'pUrl'  => preg_replace("/[^\w]/i", "", $post['address']),
			// 'tCategory'=> isset($post['tCategory'])?abs($post['tCategory']):'0',
			'tBlog' => isset($post['tblog'])?abs($post['tblog']):'0',
			'pText' => (empty($post['blog']) && isset($post['text']))?trim($post['text']):'',
			//'pImg'  => !empty($post['pImg'])?substr($post['pImg'], strlen(base_url())-1):'',
			'pOriginalImg'  => !empty($post['pOriginalImg'])?substr($post['pOriginalImg'], strlen(base_url())-1):'',
			'pShortText' => (empty($post['blog']) && isset($post['shorttext']))?trim($post['shorttext']):''
		);

		if ($id)
		{
			$upd['dUpdated'] = now();
			$upd['tUserUpdated'] = $this->user->id;
			$this->db->where('id', $id);
			$this->db->update('article', $upd);
		}
		else
		{
			$upd['dCreated'] = now();
			$upd['tUserCreated'] = $this->user->id;
			$this->db->insert('article', $upd);
			$id = $this->db->insert_id();
		}


		if (!empty($post['cropOnSave']) && ($post['cropOnSave'] == '1') && !empty($post['c']) && sizeof($post['c'])==6 && !empty($post['pOriginalImg']))
		{
			$folder = 'uploads/articles/'.$id;

			if(!is_dir(rootDir().$folder))
				mkdir(rootDir().$folder);

			if(!is_dir(rootDir().$folder.'/thumb200'))
				mkdir(rootDir().$folder.'/thumb200');

			if(!is_dir(rootDir().$folder.'/thumb30'))
				mkdir(rootDir().$folder.'/thumb30');

			if ($pImg = $this->cropImage($folder, $post['pOriginalImg'], $post['c']))
			{
                $this->db->where('id', $id)->update('article', array(
					'pImg' => $pImg
				));
			}
		}

		$this->db->delete('article_category', array('tArticle' => $id));
		if (!empty($post['selectItem_categories']) && is_array($post['selectItem_categories'])) {
			$insertCats = array();
			foreach ($post['selectItem_categories'] as $val) {
				$insertCats[]=array(
					'tArticle' => $id,
					'tCategory' => $val
				);
			}
			$this->db->insert_batch('article_category', $insertCats);
		}

		if (!empty($post['newAddStyles']))
		{
			$newAddStyles = json_decode($post['newAddStyles']);
			if (is_arr($newAddStyles))
			{
				$ins = array();
				foreach ($newAddStyles as $newStyle)
				{
					$ins[]=array(
						'tPage' => $id,
						'pUrl' => $newStyle,
						'pType' => 0,
						'pArticle' => 1
					);
				}
				if (sizeof($ins))
					$this->db->insert_batch('additional_style', $ins);
			}
		}
		
		if (!empty($post['delAddStyles']))
		{
			$delAddStyles = json_decode($post['delAddStyles']);
			if (is_arr($delAddStyles))
			{
				$this->db->where('tPage', $id);
				$this->db->where_in('id', $delAddStyles);
				$this->db->delete('additional_style');
			}
		}
		
		if (!empty($post['newAddScripts']))
		{
			$newAddScripts = json_decode($post['newAddScripts']);
			if (is_arr($newAddScripts))
			{
				$ins = array();
				foreach ($newAddScripts as $newScript)
				{
					$ins[]=array(
						'tPage' => $id,
						'pUrl' => $newScript,
						'pType' => 1,
						'pArticle' => 1
					);
				}
				if (sizeof($ins))
					$this->db->insert_batch('additional_style', $ins);
			}
		}
		
		if (!empty($post['delAddScripts']))
		{
			$delAddScripts = json_decode($post['delAddScripts']);
			if (is_arr($delAddScripts))
			{
				$this->db->where('tPage', $id);
				$this->db->where_in('id', $delAddScripts);
				$this->db->delete('additional_style');
			}
		}
		
		return $id;
	}

	function getBlogs($ids = array())
	{
		if (is_array($ids) && sizeof($ids))
			$this->db->where_in('id', $ids);
			elseif (abs($ids))
			$this->db->where('id', abs($ids));
		$this->db->where('pType', 1);
		$this->db->where('dDeleted', 0);
		$res = $this->db->get('page')->result();

		return setKeys($res, 'id');
	}

	function getPages($ids = array(), $deleted = false)
	{
		if (is_arr($ids))
			$this->db->where_in('id', $ids);
		if ($deleted)
			$this->db->where('dDeleted >', 0);
			else
			$this->db->where('dDeleted', 0);
		$this->db->order_by('pOrder desc, id desc');
		return $this->db->get('page')->result();
	}
	
	function getPage($id = 0)
	{
		if (!($id = abs($id)))
			return false;
		
		$this->db->where('id', $id);
		$this->db->where('dDeleted', 0);
		return $this->db->get('page')->row();
	}
	
	function existsUrl($url, $id = 0)
	{
		if ($url == 'admin') return true;

		if (!$this->isCorrectUrl($url))
			return true;
		
		if ($id)
			$this->db->where('id !=', abs($id));
		$this->db->where('pUrl', trim($url));
		$this->db->where('dDeleted', 0);
		return $this->db->count_all_results('page');
	}
	
	function savePage($post = array())
	{
		if (!is_arr($post) || empty($post['name']) || !isset($post['address']))
			return false;

		$id = (isset($post['id']))?abs($post['id']):0;

		if (isset($post['delete']))
		{
			if (!($id))
				return false;
			
			$this->db->where('id', $id);
			return $this->db->update('page', array(
				'dDeleted' => now(),
				'tUserDeleted' => $this->user->id
			));
		}

		if ($post['type'] == 0 || $post['type'] == 3)
		{
			if (empty($post['text']))
			{
				if ($post['inputType'] == 'markitup')
					$post['text'] = $post['text_m'];
				elseif ($post['inputType'] == 'tinymce')
					$post['text'] = $post['text_t'];
				else
					return false;
			}			
		}
		elseif ($post['type'] == 1)
			$post['text'] = '';
		elseif ($post['type'] = 2)
			$post['text'] = json_encode($post['blog']);
		
		if ($this->existsUrl($post['address'], $id))
			die('Этот короткий адрес уже используется: '.$post['address']);
		
		$upd = array(
			'pName' => $post['name'],
			'pUrl'  => preg_replace("/[^\w]/i", "", $post['address']),
			'pType' => $post['type'],
			'pMenu' => isset($post['menu'])?'1':'0',
			'pMain' => isset($post['main'])?'1':'0',
			'pText' => trim($post['text']),
			'tPage' => abs($post['tPage']),
			'pBlogSize' => abs($post['pBlogSize']),
			'pType2' => abs($post['pType2']),
			'pSize2' => abs($post['pSize2']),
		);

		if ($upd['pMain'] == '1')
		{
			$this->db->where('pMain', '1');
			$this->db->update('page', array('pMain' => 0));
		}
		
		if ($id)
		{
			$upd['dUpdated'] = now();
			$upd['tUserUpdated'] = $this->user->id;
			$this->db->where('id', $id);
			$this->db->update('page', $upd);
		}
		else
		{
			$upd['dCreated'] = now();
			$upd['tUserCreated'] = $this->user->id;
			$this->db->insert('page', $upd);
			$id = $this->db->insert_id();
		}

		if (!empty($post['feedback']) & $post['type'] == 3)
		{
			$fb = json_decode($post['feedback']);
			if (is_arr($fb))
			{
				foreach ($fb as $key => $fVal)
				{
					if (sizeof($fVal) != 3)
						unset($fb[$key]);
				}
			}

			if ($this->db->where('tPage', $id)->count_all_results('feedback'))
				$this->db->where('tPage', $id)->update('feedback', array('pJSON' => json_encode($fb)));
			else
				$this->db->insert('feedback', array(
					'pJSON' => json_encode($fb),
					'tPage' => $id
				));
		}
		
		if (!empty($post['newCategories']))
		{
			$newCategories = json_decode($post['newCategories']);
			if (is_arr($newCategories))
			{
				$ins = array();
				foreach ($newCategories as $newCategory)
				{
					$ins[]=array(
						'tPage' => $id,
						'pName' => $newCategory
					);
				}
				if (sizeof($ins))
					$this->db->insert_batch('category', $ins);
			}
		}
		
		if (!empty($post['delCategories']))
		{
			$delCategories = json_decode($post['delCategories']);
			if (is_arr($delCategories))
			{
				$this->db->where('tPage', $id);
				$this->db->where_in('id', $delCategories);
				$this->db->delete('category');
			}
		}
		
		if (!empty($post['newAddStyles']))
		{
			$newAddStyles = json_decode($post['newAddStyles']);
			if (is_arr($newAddStyles))
			{
				$ins = array();
				foreach ($newAddStyles as $newStyle)
				{
					$ins[]=array(
						'tPage' => $id,
						'pUrl' => $newStyle,
						'pType' => 0,
						'pArticle' => 0
					);
				}
				if (sizeof($ins))
					$this->db->insert_batch('additional_style', $ins);
			}
		}
		
		if (!empty($post['delAddStyles']))
		{
			$delAddStyles = json_decode($post['delAddStyles']);
			if (is_arr($delAddStyles))
			{
				$this->db->where('tPage', $id);
				$this->db->where_in('id', $delAddStyles);
				$this->db->delete('additional_style');
			}
		}
		
		if (!empty($post['newAddScripts']))
		{
			$newAddScripts = json_decode($post['newAddScripts']);
			if (is_arr($newAddScripts))
			{
				$ins = array();
				foreach ($newAddScripts as $newScript)
				{
					$ins[]=array(
						'tPage' => $id,
						'pUrl' => $newScript,
						'pType' => 1,
						'pArticle' => 0
					);
				}
				if (sizeof($ins))
					$this->db->insert_batch('additional_style', $ins);
			}
		}
		
		if (!empty($post['delAddScripts']))
		{
			$delAddScripts = json_decode($post['delAddScripts']);
			if (is_arr($delAddScripts))
			{
				$this->db->where('tPage', $id);
				$this->db->where_in('id', $delAddScripts);
				$this->db->delete('additional_style');
			}
		}
		
		return $id;
	}
	
	function getCategories($tPage = 0)
	{
		if ($tPage)
			$this->db->where('tPage', $tPage);
		else
		{
			$blogs = $this->getBlogs();
			if (!is_arr($blogs))
				return array();
			$this->db->where_in('tPage', extractFieldFromDataArray($blogs, 'id'));
		}
		return $this->db->get('category')->result();
	}
	
	function getBlocks()
	{
		return $this->db->get('blocks')->result();
	}
	
	function getBlock($id = 0)
	{
		$this->db->where('id', $id);
		return $this->db->get('blocks')->row();
	}
	
	function saveBlock($post)
	{
		$this->db->where('id', $post['id']);
		if ($this->db->update('blocks', array(
			'pText' => $post['text']
		)))
			return abs($post['id']);
			else
			return false;
	}

	function cropImage($folder, $img, $c)
	{
		//if (array_sum($c) == 0) return $img;
		if (!$img)
			return false;

		$img = rootDir().substr($img, strlen(base_url()));
	
		if (!file_exists($img))
			return false;

        $fileinfo = getimagesize($img);
		switch ($fileinfo['mime'])
		{
			case 'image/png':						
				$old = imagecreatefrompng($img);
				if (!$old) return false;
                $fileType = 'png';
                break;
            case 'image/jpeg':
                $old = imagecreatefromjpeg($img);
                if (!$old) return false;
                $fileType = 'jpg';
                break;
            case 'image/gif':
                $old = imagecreatefromgif($img);
                if (!$old) return false;
                $fileType = 'gif';
                break;
			default:
				return false;
		}

        $fileName = array_slice(explode('/', $img), -1);
        $fileName = substr($fileName[0], 0, strrpos($fileName[0], '.')).'.'.$fileType;
        $file200 = rootDir().$folder.'/thumb200/'.$fileName;
        $file30 = rootDir().$folder.'/thumb30/'.$fileName;

        if (empty($c['x'])) $c['x'] = 0;
        if (empty($c['y'])) $c['y'] = 0;
        if (empty($c['w'])) $c['w'] = min($fileinfo[0], $fileinfo[1]);
        if (empty($c['h'])) $c['h'] = min($fileinfo[0], $fileinfo[1]);

        if (
            $this->saveImage($fileType, $old, $file200, $c, 200) &&
            $this->saveImage($fileType, $old, $file30, $c, 30)
        ) {
            return $fileName;
        } else {
            return false;
        }
	}

    function saveImage($fileType, $old, $path, $c, $size)
    {
        switch ($fileType) {
            case 'jpg':
                $new = imagecreatetruecolor($size, $size);
                imagecopyresampled($new, $old, 0, 0, $c['x'], $c['y'], $size, $size, $c['w'], $c['h']);
                imagejpeg($new, $path, 85);
                break;
            case 'png':
                $new = imagecreatetruecolor($size, $size);
                imagealphablending($new, false);
                imagesavealpha($new, true);
                imagecopyresampled($new, $old, 0, 0, $c['x'], $c['y'], $size, $size, $c['w'], $c['h']);
                imagepng($new, $path);
                break;
            case 'gif':
                $new = imagecreatetruecolor($size, $size);
                $transparent_source_index = imagecolortransparent($old);
                if ($transparent_source_index !== -1){
                    $transparent_color = imagecolorsforindex($old, $transparent_source_index);
                    $transparent_destination_index = imagecolorallocate($new, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
                    imagecolortransparent($new, $transparent_destination_index);
                    imagefill($new, 0, 0, $transparent_destination_index);
                }
                imagecopyresampled($new, $old, 0, 0, $c['x'], $c['y'], $size, $size, $c['w'], $c['h']);
                imagegif($new, $path);
                break;
            default:
                return false;
        }
        return true;
    }
	
	function getBlogsStats()
	{
		$this->db->select('id, pName');
		$this->db->where('pType', 1);
		$this->db->where('dDeleted', 0);
		$pages = $this->db->get('page')->result();
		
		if (!$pages)
			return array();
		$ids = extractFieldFromDataArray($pages, 'id');
		
		$this->db->select('tBlog, count(id) as "count"');
		$this->db->where_in('tBlog', $ids);
		$this->db->where('dDeleted', 0);
		$this->db->where('dAllowed >', 0);
		$this->db->group_by('tBlog');
		$blogs = setKeys($this->db->get('article')->result(), 'tBlog');
		
		$exp = array();
		foreach ($pages as $page)
		{
			$exp[$page->id] = (object)array(
				'id' => $page->id,
				'pName' => $page->pName,
				'count' => isset($blogs[$page->id])?$blogs[$page->id]->count:0
			);
		}
		
		return $exp;
	}
	
	function getUsersCount()
	{
		return $this->db->count_all('user');
	}

	function savePagesOrder($post)
	{
		if (empty($post['page']))
			return false;

		foreach ($post['page'] as $pageId=>$order)
		{
			$this->db->where('id', $pageId)->update('page', array('pOrder'=>$order));
		}

		return true;
	}

	function getComments($deleted = false, $page = 1)
	{
		if ($deleted)
			$this->db->where('dDeleted >', 0);
		else
			$this->db->where('dDeleted', 0);

		$limit = AdminVars::$pageSize;
		$offset = abs($page-1) * $limit;
		return $this->db->order_by('id desc')->get('comment', $limit, $offset)->result();
	}

	function getUsers($page = 1)
	{
		$limit = AdminVars::$pageSize;
		$offset = abs($page-1) * $limit;
		return $this->db->get('user', $limit, $offset)->result();
	}

	function getVisites()
	{
		// $vis =  $this->db->query('SELECT p.cnt, p.tId, p.pType FROM (SELECT COUNT(tId) as "cnt", visit.* FROM visit GROUP BY pType, tId) p ORDER BY p.cnt desc')->result();
		$vis = $this->db->select('COUNT(tId) as "cnt", v.*')->group_by('pType, tId')->order_by('cnt desc')->get('visit v')->result();

		$pages = $articles = array();
		foreach ($vis as $val) {
			if ($val->pType == 0)
				$pages[]=$val->tId;
			else
				$articles[]=$val->tId;
		}
		
		if (!empty($articles))
		{
			$articles = $this->db->select('id, pName')->where_in('id', $articles)->where('dDeleted', 0)->get('article')->result();
			$articles = setKeys($articles, 'id');
		}

		if (!empty($pages))
		{
			$pages = $this->db->select('id, pName')->where_in('id', $pages)->where('dDeleted', 0)->get('page')->result();
			$pages = setKeys($pages, 'id');
		}

		foreach ($vis as $key => $val) {
			$vis[$key]->page = ($val->pType == 0)?$pages[$val->tId]:$articles[$val->tId];
		}

		return $vis;
	}

	function getPageVisites($type = 0, $id = 0)
	{
		return $this->db->where('pType', $type)->where('tId', $id)->order_by('dCreated desc')->get('visit')->result();
	}

	public function getUpLevelPages($id = 0)
	{
		return $this->db->select('id, pName')->where(array(
			'tPage' => 0,
			'dDeleted' => 0,
			'dAllowed >' => 0,
			'id != ' => $id,
		))->get('page')->result();
	}
	
	function isCorrectUrl($url='')
	{
		if ($url == 'admin')
			return false;
		$this->load->helper('file_helper');
		$controllers = get_filenames(rootDir().APPPATH.'controllers');

		foreach ($controllers as $val)
		{
			if ($url == substr($val, 0, -4))
				return false;
		}
		return true;
	}

	function getBlogSize($id=0)
	{
		$res = $this->db
			->where('tPage', $id)
			->get('page_blog_settings')
			->row();
		return $res? abs($res->pBlogSize): 0;
	}

	public function getAddStyles($id = 0, $isArticle = false)
	{
		return $this->db
			->where(array(
				'tPage' => $id,
				'dDeleted' => 0,
				'pType' => 0,
				'pArticle' =>  abs($isArticle)
			))->get('additional_style')->result();
	}

	public function getAddScripts($id = 0, $isArticle = false)
	{
		return $this->db
			->where(array(
				'tPage' => $id,
				'dDeleted' => 0,
				'pType' => 1,
				'pArticle' =>  abs($isArticle)
			))->get('additional_style')->result();
	}

}
?>